package com.rivues.module.platform.web.handler;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;
import org.rivu.handler.GeneraDAO;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.SessionAttributes;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.view.RedirectView;

import com.rivues.core.RivuDataContext;
import com.rivues.module.platform.web.model.Cube;
import com.rivues.module.platform.web.model.CubeLevel;
import com.rivues.module.platform.web.model.CubeMeasure;
import com.rivues.module.platform.web.model.CubeMetadata;
import com.rivues.module.platform.web.model.Dimension;
import com.rivues.module.platform.web.model.MonitorAccessStatistics;
import com.rivues.module.platform.web.model.PublishedCube;
import com.rivues.module.platform.web.model.QueryLog;
import com.rivues.module.platform.web.model.User;
import com.rivues.util.RivuTools;
import com.rivues.util.log.Logger;
import com.rivues.util.log.LoggerFactory;

@Controller
@SessionAttributes
public class Handler {
	protected Logger log = null ;    
	public final static int PAGE_SIZE_BG = 1 ;
	public final static int PAGE_SIZE_TW = 20 ;
	public final static int PAGE_SIZE_FV = 50 ;
	public final static int PAGE_SIZE_HA = 100 ;
	private String orgi ;
	private String flowid ;
	private Date intime ;
	private boolean error ;
	private Object currentMethod ;
	
	public User getUser(HttpServletRequest request){
		User user = (User) request.getSession(true).getAttribute(RivuDataContext.USER_SESSION_NAME)  ;
		if(user==null){
			user = new User();
			user.setUsername(RivuDataContext.GUEST_USER) ;
			user.setId(RivuTools.md5(request.getSession(true).getId())) ;
		}
		user.setSessionid(request.getSession(true).getId()) ;
		return user ;
	}
	
	public GeneraDAO getService(){
		return RivuDataContext.getService() ;
	}
	
	/**
	 * 
	 * @param path
	 * @return
	 */
	public ModelAndView request(String path) {
		return new ModelAndView(path);
    }
	/**
	 * 
	 * @param data
	 * @return
	 */
	public ModelAndView request(ResponseData data , String orgi) {
		ModelAndView view = new ModelAndView(data.getTemplet()!=null ? data.getTemplet(): data.getPage() , "data", data); 
		if(data.getTemplet()!=null && data.getPage()!=null){
			view.addObject("page", data.getPage()) ;
		}
		view.addObject("orgi", orgi) ;
    	return view ;
    }
	/**
	 * 
	 * @param orgi
	 * @param cube
	 * @param metadata
	 * @return
	 */
	public Cube loadCubeData(String orgi , Cube cube , boolean metadata){
		if(cube!=null){
			List<CubeMetadata> metaList = getService().findAllByCriteria(DetachedCriteria.forClass(CubeMetadata.class).add(Restrictions.and(Restrictions.eq("orgi", orgi) , Restrictions.eq("cube", cube.getId())))) ;
			cube.getMetadata().clear();
			cube.getMetadata().addAll(metaList);
			
			List<Dimension> dimeasionList = getService().findAllByCriteria(DetachedCriteria.forClass(Dimension.class).add(Restrictions.and(Restrictions.eq("orgi", orgi) , Restrictions.eq("cubeid", cube.getId()))).addOrder(Order.desc("createtime"))) ;
			for (int i = 0; i < dimeasionList.size(); i++) {
				List<CubeLevel> levels = getService().findAllByCriteria(DetachedCriteria.forClass(CubeLevel.class)
					.add(Restrictions.eq("orgi", orgi))
					.add(Restrictions.eq("dimid", dimeasionList.get(i).getId()))
					.addOrder(Order.asc("sortindex")));
				dimeasionList.get(i).getCubeLevel().clear();
				dimeasionList.get(i).getCubeLevel().addAll(levels);
			}
			cube.getDimension().clear();
			cube.getDimension().addAll(dimeasionList);
			
			List<CubeMeasure> cubeMeasureList = getService().findAllByCriteria(DetachedCriteria.forClass(CubeMeasure.class).add(Restrictions.and(Restrictions.eq("orgi", orgi) , Restrictions.eq("cubeid", cube.getId())))) ;
			cube.getMeasure().clear();
			cube.getMeasure().addAll(cubeMeasureList);
			
			
		}
		return cube ;
	}
	/**
	 * 
	 * @param data
	 * @return
	 */
	public ModelAndView request(ResponseData data , Map<String, Object> dataMap) {
		dataMap.put("data", data) ;
    	return new ModelAndView(data.getPage() , dataMap);
    }
	/**
	 * 
	 * @param data
	 * @return
	 */
	public ModelAndView request(ResponseData data , RequestData rqdata) {
    	return new ModelAndView(rqdata.getQ()!=null ? new StringBuffer().append(data.getPage()).append(data.getPage().indexOf("\\?")<0 ? "?":"").append(rqdata.getQ()).toString() : data.getPage() , "data", data);
    }
	/**
	 * 根据租户ID找到该租户发布的所有模型
	 * @param orgi
	 * @return
	 */
	public List<PublishedCube> getPublishedCubeList(String orgi){
		return getService().findAllByCriteria(DetachedCriteria.forClass(PublishedCube.class).add(Restrictions.eq("orgi", orgi))) ;
	}
	
	/**
	 * 重定向
	 * @param redirectView
	 * @return
	 */
	public ModelAndView request(RedirectView redirectView) {
    	return new ModelAndView(redirectView);
    }
	/**
	 * 记录日志
	 * @param log
	 */
	@SuppressWarnings("unchecked")
	public void processLog(QueryLog log){
		getService().saveIObject(log);
	}
	
	/**
	 * 数据分页
	 * @param request
	 * @param orgi
	 * @param view
	 * @param criteria
	 * @param beginNumName
	 * @param endNumName
	 * @param dataName
	 * @return
	 */
	public ModelAndView page(HttpServletRequest request,String orgi,ModelAndView view,DetachedCriteria criteria,String beginNumName,String endNumName,String dataName){
		//分页数据组装
		List list = new ArrayList();
		int beginNum = PAGE_SIZE_BG;
    	if(request.getParameter("beginNum")!=null&&!"".equals(request.getParameter("beginNum"))){
    		beginNum = Integer.valueOf(request.getParameter("beginNum"));
    	}
		int endNum = PAGE_SIZE_TW;
		if(request.getParameter("endNum")!=null&&!"".equals(request.getParameter("endNum"))){
			endNum = Integer.valueOf(request.getParameter("endNum"));
		}
		int allrow = getService().getCountByCriteria(criteria);
		int current = beginNum;
		if(allrow>0){
			int pageSize = endNum-beginNum;
			if(pageSize<0)pageSize=0;
			String action = request.getParameter("action");
			
			if("first".equals(action)){
				current=1;
			}else if("last".equals(action)){
				current=beginNum-1-pageSize>0?beginNum-pageSize-1:1;
			}else if("next".equals(action)){
				if(endNum<=allrow)
				current=endNum+1;
			}else if("final".equals(action)){
				current=allrow-pageSize+1;
			}
			if(current<1)current=1;
			if(current>allrow)current=allrow;
			list = getService().findPageByCriteria(criteria, pageSize+1 ,current-1,true) ;
			if(pageSize!=0){
				endNum = current+pageSize;
			}
//			if(endNum>allrow){
//				endNum = allrow;
//			}
			if(endNum<=0){
				endNum = 1;
			}
		}
		view.addObject(dataName, list);
		view.addObject(beginNumName,current);
		view.addObject(endNumName,endNum);
		return view;
	}
	
	protected void info(String info) {
		if(log!=null){
			log.info(info, orgi, flowid) ;
		}else{
			System.out.println(info);
		}
	}

	public String getOrgi() {
		return orgi;
	}

	public void setOrgi(String orgi) {
		this.orgi = orgi;
	}

	public String getFlowid() {
		return flowid;
	}

	public void setFlowid(String flowid) {
		this.flowid = flowid;
	}

	public Logger getLog() {
		return log;
	}

	public void setLog(Logger log) {
		this.log = log;
	}

	public Date getIntime() {
		return intime;
	}

	public void setIntime(Date intime) {
		this.intime = intime;
	}

	public boolean isError() {
		return error;
	}

	public void setError(boolean error) {
		this.error = error;
	}

	public Object getCurrentMethod() {
		return currentMethod;
	}

	public void setCurrentMethod(Object currentMethod) {
		this.currentMethod = currentMethod;
	}
	/**
	 * 创建 系统管理的 模板页面
	 * @param page
	 * @return
	 */
	public ResponseData createManageTempletResponse(String page) {
		return new ResponseData("/pages/manage/index" , page);
	}
	
	
	/**
	 * 创建 报表辅助的 模板页面
	 * @param page
	 * @return
	 */
	public ResponseData createAssistTempletResponse(String page) {
		return new ResponseData("/pages/assist/index" , page);
	}
	
	/**
	 * 创建系统监控的 模板页面
	 * @param page
	 * @return
	 */
	public ResponseData createMonitorTempletResponse(String page) {
		return new ResponseData("/pages/monitor/index" , page);
	}
	/**
	 * 创建系统监控的 模板页面
	 * @param page
	 * @return
	 */
	public ResponseData createOperationMonitorTempletResponse(String page) {
		return new ResponseData("/pages/monitor/operation/index" , page);
	}
	
	/**
	 * 创建 系统管理的 模板页面
	 * @param page
	 * @return
	 */
	public ResponseData createReportTempletResponse(String page) {
		return new ResponseData("/pages/report/index" , page);
	}
	
	/**
	 * 创建 模型管理的 模板页面
	 * @param page
	 * @return
	 */
	public ResponseData createDMTempletResponse(String page) {
		return new ResponseData("/pages/datamodel/index" , page);
	}
	/**
	 * 创建 系统管理的 跳转页面
	 * @param page
	 * @return
	 */
	public ResponseData createPageResponse(String page) {
		return new ResponseData(page);
	}
	/**
	 * 创建 系统管理的 跳转页面
	 * @param page
	 * @return
	 */
	public ResponseData createManageResponse(String page) {
		return new ResponseData(page);
	}
}
